import React, { useState, useEffect, useCallback, Key, useRef } from 'react';
import type { ProColumns, ProTableProps } from '@ant-design/pro-table';
import { ProTable, MyProTableProps } from '@/components/KaiyaTable/index';
import {
  Modal,
  Tree,
  Select,
  Input,
  Button,
  message,
  Form,
  FormInstance,
} from 'antd';
import { FilterOutlined, PlusOutlined } from '@ant-design/icons';
import request from 'umi-request';
import { history } from 'umi';
import moment from 'moment';

import {
  getUserList,
  getOrgTree,
  updateUserStatus,
  deleteUserById,
  updateUserPassword,
  resetPassword,
} from '@/services/userControl';
import { copyFun, getStorageData } from '@/utils/tools';
import Const from '@/utils/Const';

import { connect } from 'dva';

interface UserManage {
  getUserListDispatch: (msg: object, data: any) => void;
  getOrgTreeDispatch: (parmas: object) => void;
}

interface TreecheckedRows {
  keys: string[];
  rows: any[];
}

const UserManage: React.FC<UserManage> = (props) => {
  console.log('UserManage', props);
  const { getUserListDispatch, getOrgTreeDispatch } = props;
  const tableRef = useRef<any>();
  const formRef = useRef<any>();
  const passwordRef = useRef<any>();
  const [departmentTree, setdepartmentTree] = useState([]);
  const [checkedKeys, setcheckedKeys] = useState([]);
  const [checkedRows, setcheckedRows] = useState([]);
  const [checkedTitles, setcheckedTitles] = useState([]);
  const [selectedRowKeys, setselectedRowKeys] = useState([]);
  const [passwordModalMsg, setpasswordModalMsg] = useState({
    modalShow: false,
    id: '',
    oldPassword: '',
    newPassword: '',
  });
  const [treeModalVisible, settreeModalVisible] = useState<boolean | undefined>(
    false,
  );
  const TableCustomDeploy = {
    componentName: 'customTable',
  };
  const ref = useRef<FormInstance>();

  useEffect(() => {
    getDepartmentTreeByRole();
  }, []);
  const getUserData = async (params) => {
    let res = await getUserList(params);
    let lastData = {
      ...res,
      page: res.currentPage,
      total: res.totalRecords,
      success: true,
    };
    console.log('getUserData', params);
    console.log('lastData', lastData);
    return Promise.resolve(lastData);
  };
  const requestHandle = async (params: any) => {
    let res = await request('/api/users', {
      method: 'GET',
      params,
    });
    return Promise.resolve(res);
  };

  const getDepartmentTreeByRole = async () => {
    let userType = getStorageData('userInfo').userType;
    let res = await getOrgTree({ orgType: userType === 1 ? 0 : 1 });
    setdepartmentTree(formatTreeData(res?.data));
  };
  const modalOkHandle = () => {
    console.log('ok');
  };
  const addHandle = () => {
    history.push({
      pathname: '/features/userPermission/user/add',
      state: {
        pageType: 'add',
      },
    });
  };
  const updateUserStatusPost = async (
    arrId: number[],
    status: string,
    text: string,
  ) => {
    console.log(arrId, status);
    Modal.warning({
      title: `${text}提示信息`,
      content: `${
        status === '1'
          ? `确认${text}所选用户？`
          : '停用角色后，该角色将无法使用，请确认是否停用！'
      }`,
      closable: true,
      okText: '确认',
      onOk: async () => {
        const res = await updateUserStatus({ ids: arrId, status });
        if (res.code === 200) {
          message.success(`${text}成功`);
          tableRef.current.reloadAndRest();
        } else {
          message.error(res.message);
        }
      },
    });
  };
  const formatTreeData = (data: any) => {
    if (Array.isArray(data) && data.length > 0) {
      data.forEach((ele) => {
        ele.title = ele.name;
        ele.key = ele.id;
        if (ele.children && ele.children.length > 0) {
          formatTreeData(ele.children);
        }
      });
    }
    return data;
  };

  const passwordModalOnOkHandle = async () => {
    try {
      const values = await formRef.current.validateFields();
      const res = await updateUserPassword({});
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  };
  const getTableBasicDeploy = (): ProTableProps<any, any, any> => {
    const columns: ProColumns[] = [
      {
        dataIndex: 'index',
        title: '序号',
        valueType: 'indexBorder',
      },
      {
        title: '用户名',
        dataIndex: 'name',
        valueType: 'text',
        order: 1,
      },
      {
        title: '用户类型',
        dataIndex: 'type',
        valueType: 'select',
        order: 3,
        valueEnum: {
          // 1: { text: '企业管理员' },
          2: { text: '普通管理员' },
          3: { text: '普通用户' },
        },
      },
      {
        title: '创建者',
        dataIndex: 'createdBy',
        valueType: 'text',
        hideInSearch: true,
      },
      {
        title: '创建日期',
        dataIndex: 'createdTime',
        valueType: 'dateRange',
        hideInSearch: true,
        render: (text, record, _, action) => {
          return <span>{moment(record.createdTime).format('YYYY-MM-DD')}</span>;
        },
      },
      {
        title: '归属机构',
        dataIndex: 'organizationName',
        valueType: 'text',
        order: 4,
        renderFormItem: (_, { defaultRender }) => {
          return (
            <Input
              value={
                checkedTitles?.length > 0 ? checkedTitles.join('，') : '请选择'
              }
              onClick={() => {
                settreeModalVisible(true);
              }}
            />
          );
        },
      },
      {
        title: '状态',
        dataIndex: 'status',
        valueType: 'select',
        order: 2,
        valueEnum: {
          '0': { text: '停用' },
          '1': { text: '启用' },
          '2': { text: '锁定' },
          '3': { text: '过期' },
        },
      },
      {
        title: '操作',
        valueType: 'option',
        render: (text, record, _, action) => [
          <a
            href={record.url}
            target="_blank"
            rel="noopener noreferrer"
            key="view"
            onClick={() => {
              history.push({
                pathname: '/features/userPermission/user/add',
                state: {
                  pageType: 'details',
                  userId: record.id,
                },
              });
            }}
          >
            详情
          </a>,
          <a
            href={record.url}
            target="_blank"
            rel="noopener noreferrer"
            key="view"
            onClick={() => {
              history.push({
                pathname: '/features/userPermission/user/add',
                state: {
                  pageType: 'edit',
                  userId: record.id,
                },
              });
            }}
          >
            编辑
          </a>,
          <a
            target="_blank"
            rel="noopener noreferrer"
            key="view"
            onClick={() => {
              Modal.warning({
                title: '重置密码提示信息',
                content: '确定要重置密码吗？',
                closable: true,
                okText: '确认',
                onOk: async () => {
                  const res = await resetPassword(record.id);
                  Modal.success({
                    title: '重置密码提示信息',
                    content: (
                      <div>
                        <div>密码重置成功！该用户下次登陆须修改密码!</div>
                        <div>
                          重置密码为：
                          <strong ref={passwordRef}>{res.data}</strong>
                        </div>
                      </div>
                    ),
                    closable: true,
                    okText: '复制密码',
                    cancelText: '确认',
                    onOk: async () => {
                      copyFun(res.data);
                      message.success(`复制成功`);
                    },
                  });
                },
              });
            }}
          >
            重置密码
          </a>,
          <a
            target="_blank"
            rel="noopener noreferrer"
            key="view"
            onClick={async () => {
              Modal.warning({
                title: '删除提示信息',
                content: '删除用户后，该用户将无法登录，且无法恢复！',
                closable: true,
                okText: '确认',
                onOk: async () => {
                  const id = record.id;
                  const res = await deleteUserById(id);
                  console.log(res);
                  if (res.code === 200) {
                    message.success(`删除成功`);
                    tableRef.current.reloadAndRest();
                  }
                },
              });
            }}
          >
            删除
          </a>,
          // <a
          //   href={record.url}
          //   target="_blank"
          //   rel="noopener noreferrer"
          //   key="view"
          //   onClick={(record) => {
          //     console.log(record);
          //   }}
          // >
          //   更多
          // </a>,
        ],
      },
    ];
    const rowSelection = {
      onChange: (selectedRowKeys: React.Key[], selectedRows: any[]) => {
        setselectedRowKeys(selectedRowKeys);
      },
      getCheckboxProps: (record: any) => ({
        disabled: record.name === 'Disabled User', // Column configuration not to be checked
        name: record.name,
      }),
    };
    return {
      actionRef: tableRef,
      columns,
      request: async (params = {}, sort, filter) => {
        console.log('request请求发出', params, filter);
        let lastParams = {
          ...params,
          employeeOrganizationId: checkedKeys,
          pageNumber: params.current,
          pageSize: params.pageSize,
        };
        delete lastParams.current;
        return getUserData(lastParams);
      },
      onReset: () => {
        setcheckedTitles([]);
        setcheckedKeys([]);
        ref.current?.submit();
      },
      formRef: ref,
      rowSelection: {
        type: 'checkbox',
        ...rowSelection,
      },
      pagination: {
        pageSize: 5,
      },
      rowKey: 'id',
      onReset:()=>{
        setcheckedKeys([]);
        setcheckedRows([]);
        setcheckedTitles([]);
      },
      toolBarRender: () => [
        <Button icon={<PlusOutlined />} onClick={addHandle}>
          新增用户
        </Button>,
        <Button
          onClick={() => {
            updateUserStatusPost(selectedRowKeys, '1', '解锁');
          }}
        >
          解锁
        </Button>,
        <Button
          onClick={() => {
            updateUserStatusPost(selectedRowKeys, '0', '停用');
          }}
        >
          停用
        </Button>,
        <Button
          onClick={() => {
            updateUserStatusPost(selectedRowKeys, '1', '启用');
          }}
        >
          启用
        </Button>,
      ],
    };
  };
  const jsonOption: MyProTableProps = {
    TableCustomDeploy,
    TableBasicDeploy: getTableBasicDeploy,
  };
  const modalOnOkHandle = () => {
    console.log(checkedRows, checkedKeys);
    let rowsByTitle = checkedRows
      .map((item: any) => {
        // if(item.children === null){
        return item.title;
        // }
      })
      .filter(Boolean);
    console.log(rowsByTitle);
    setcheckedTitles(rowsByTitle);
    settreeModalVisible(false);
  };
  return (
    <div>
      <Modal
        title="组织架构"
        visible={treeModalVisible}
        onOk={modalOnOkHandle}
        onCancel={() => {
          setcheckedTitles([]);
          setcheckedKeys([]);
          settreeModalVisible(false);
        }}
      >
        <Tree
          style={{ maxHeight: '50vh', overflowY: 'auto' }}
          checkable
          autoExpandParent={true}
          checkedKeys={checkedKeys}
          onCheck={(checkedKeysValue: any, checkedRow: any) => {
            console.log(checkedKeysValue)
            setcheckedKeys(checkedKeysValue);
            setcheckedRows(checkedRow.checkedNodes);
          }}
          treeData={departmentTree}
        />
      </Modal>
      <Modal
        title="重置密码"
        visible={passwordModalMsg.modalShow}
        onOk={passwordModalOnOkHandle}
        onCancel={() => {
          setpasswordModalMsg({
            ...passwordModalMsg,
            modalShow: false,
          });
        }}
      >
        <Form ref={formRef}>
          <Form.Item
            name="newPassword"
            label="新密码"
            rules={[
              {
                required: true,
                message: '请输入新密码!',
              },
              {
                pattern: Const.passwordReg,
                message: '密码必须是数字字母8到15位',
              },
            ]}
          >
            <Input placeholder="请输入新密码"></Input>
          </Form.Item>
        </Form>
      </Modal>
      <ProTable {...jsonOption}></ProTable>
    </div>
  );
};

const mapStateToProps = (state: any) => {
  return {};
};

const mapDispatchToProps = (dispatch: any) => {
  return {
    getUserListDispatch(msg: object, callbackData: any) {
      dispatch({
        type: 'userControl/getUserList',
        payload: msg,
        callback: (res: any) => {
          callbackData(res);
        },
        onerror: (err: any) => {
          console.log(err);
        },
      });
    },
    getOrgTreeDispatch(params: object) {
      dispatch({
        type: 'userControl/getOrgTree',
        payload: params,
        callback: (res: any) => {
          // callbackData(res);
          // return Promise.resolve(res);
          // console.log(res)
        },
        onerror: (err: any) => {
          console.log(err);
        },
      });
    },
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(UserManage);
